import { createRouter, createWebHistory } from 'vue-router'
import { useTokenStore } from '@/store/token' // 引入你的token store
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/Login/login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/forgetpwd',
      component: () => import('@/views/Login/forgetpw.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/register',
      component: () => import('@/views/register/index.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      component: () => import('@/views/Home/index.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/search',
      component: () => import('@/views/search/index.vue'),
      // meta: { requiresAuth: true },
      children: [
        {
          path: 'clothes',
          name: 'searchClothes',
          component: () => import('@/views/search/subRoutes/searchClothes.vue')
        },
        {
          path: 'store',
          name: 'searchStore',
          component: () => import('@/views/search/subRoutes/searchStore.vue')
        },
        {
          path: 'wholesale',
          name: 'searchWholesale',
          component: () => import('@/views/search/subRoutes/searchWholesale.vue')
        },
        {
          path: 'factory',
          name: 'searchFactory',
          component: () => import('@/views/search/subRoutes/searchFactory.vue')
        },
        {
          path: 'crowdfunding',
          name: 'searchCrowdfunding',
          component: () => import('@/views/search/subRoutes/searchCrowdfunding.vue')
        }
      ]
    },
    {
      path: '/userView',
      component: () => import('@/views/Home/storeHome.vue')
    },
    {
      path: '/storeView',
      component: () => import('@/views/Home/wholesalerHome.vue')
    },
    {
      path: '/wholesalerView',
      component: () => import('@/views/Home/factoryHome.vue')
    },
    {
      path: '/store',
      component: () => import('@/views/store/index.vue'),
      redirect: '/store/info',
      meta: {
        requiresAuth: true,
        role: 1  // 实体店
      },
      children: [
        {
          path: 'info',
          name: 'StoreInfo',
          component: () => import('@/views/store/subRoutes/storeInfo.vue')
        },
        {
          path: 'good',
          name: 'StoreGoods',
          component: () => import('@/views/store/subRoutes/storeGoods.vue')
        },
        {
          path: 'order',
          name: 'StoreOrder',
          component: () => import('@/views/store/subRoutes/storeOrder.vue')
        },
        {
          path: 'purchase',
          name: 'StorePurchase',
          component: () => import('@/views/store/subRoutes/storePurchase.vue')
        },
        {
          path: 'project',
          name: 'StoreProject',
          component: () => import('@/views/store/subRoutes/storeProject.vue')
        },
        {
          path: 'message',
          name: 'StoreMessage',
          component: () => import('@/views/store/subRoutes/storeMessage.vue')
        },
        {
          path: 'data',
          name: 'StoreData',
          component: () => import('@/views/store/subRoutes/storeData.vue')
        },
      ]
    },
    {
      path: '/wholesaler',
      component: () => import('@/views/wholesaler/index.vue'),
      redirect: '/wholesaler/info',
      meta: {
        requiresAuth: true,
        role: 2  // 批发商
      },
      children: [
        {
          path: 'info',
          name: 'wholesalerInfo',
          component: () => import('@/views/wholesaler/subRoutes/wholesalerInfo.vue')
        },
        {
          path: 'good',
          name: 'wholesalerGoods',
          component: () => import('@/views/wholesaler/subRoutes/wholesalerGoods.vue')
        },
        {
          path: 'order',
          name: 'wholesalerOrder',
          component: () => import('@/views/wholesaler/subRoutes/wholesalerOrder.vue')
        },
        {
          path: 'purchase',
          name: 'wholesalerPurchase',
          component: () => import('@/views/wholesaler/subRoutes/wholesalerPurchase.vue')
        },
        {
          path: 'project',
          name: 'wholesalerProject',
          component: () => import('@/views/wholesaler/subRoutes/wholesalerProject.vue')
        },
        {
          path: 'message',
          name: 'wholesalerMessage',
          component: () => import('@/views/wholesaler/subRoutes/wholesalerMessage.vue')
        },
        {
          path: 'data',
          name: 'wholesalerData',
          component: () => import('@/views/wholesaler/subRoutes/wholesalerData.vue')
        },
      ]
    },
    {
      path: '/factory',
      component: () => import('@/views/factory/index.vue'),
      redirect: '/factory/info',
      meta: {
        requiresAuth: true,
        role: 3  // 加工厂
      },
      children: [
        {
          path: 'info',
          name: 'factoryInfo',
          component: () => import('@/views/factory/subRoutes/factoryInfo.vue')
        },
        {
          path: 'good',
          name: 'factoryGoods',
          component: () => import('@/views/factory/subRoutes/factoryGoods.vue')
        },
        {
          path: 'order',
          name: 'factoryOrder',
          component: () => import('@/views/factory/subRoutes/factoryOrder.vue')
        },
        {
          path: 'project',
          name: 'factoryProject',
          component: () => import('@/views/factory/subRoutes/factoryProject.vue')
        },
        {
          path: 'projectOrders/:id',
          name: 'crowdfunding-orders',
          component: () => import('@/views/factory/subRoutes/factoryProjectOrders.vue')
        },
        {
          path: 'message',
          name: 'factoryMessage',
          component: () => import('@/views/factory/subRoutes/factoryMessage.vue')
        },
        {
          path: 'data',
          name: 'factoryData',
          component: () => import('@/views/factory/subRoutes/factoryData.vue')
        },
      ]
    },
    // {
    //   path: '/',
    //   component: () =>import('@/views/Layout/index.vue'),
    // },
    {
      path: '/member',
      component: () => import('@/views/member/index.vue'),
      redirect: '/member/info',
      meta: {
        requiresAuth: true,
        role: 0  // 普通会员
      },
      children: [
        {
          path: 'info',
          component: () => import('@/views/member/components/memberInfo.vue'),
        },
        {
          path: 'order',
          component: () => import('@/views/member/components/memberOrder.vue')
        },
        // {
        //   path: 'userCenter',
        //   component: () => import('@/views/member/components/UserInfo/components/userCenter.vue')
        // },
        // {
        //   path: 'userSetting',
        //   component: () => import('@/views/member/components/UserInfo/components/userSetting.vue')
        // },
        // {
        //   path: 'userAddress',
        //   component: () => import('@/views/member/components/UserInfo/components/userAdress.vue')
        // },
        // {
        //   path: 'crowdFunding',
        //   component: () => import('@/views/member/components/UserCrowdFunding/index.vue')
        // },
        // {
        //   path: 'message',
        //   component: () => import('@/views/member/components/UserMessage/index.vue')
        // }
      ]
    },
    {
      path: '/crowdFunding',
      component: () => import('@/views/crowdFunding/index.vue'),
    },
    {
      path: '/crowdFundingDetail/:projectid',
      name: 'crowdFundingDetail',
      component: () => import('@/views/crowdFunding/detail.vue')
    },
    {
      path: '/crowdFunding/launchCrowdFunding/:goodId',
      name: 'launchCrowdFunding',
      component: () => import('@/views/crowdFunding/launchCrowdFunding.vue')
    },
    {
      path: '/shop',
      component: () => import('@/views/shop/index.vue')
    },
    // {
    //   path: '/goodSearch',
    //   name: 'goodSearch',
    //   component: () => import('@/views/search/components/goodSearch.vue')
    // },
    // {
    //   path: '/storeSearch',
    //   name: 'storeSearch',
    //   component: () => import('@/views/search/components/storeSearch.vue')
    // },
    {
      path: '/join',
      name: 'join',
      component: () => import('@/views/join/index.vue')
    },
    {
      path: '/joinOk',
      name: 'joinOk',
      component: () => import('@/views/join/joinOk.vue')
    },
    {
      path: '/goodDetail/:userId/:goodId',
      name: 'goodDetail',
      component: () => import('@/views/detail/GoodDetail.vue')
    },
    {
      path: '/storeDetail/:userId',
      name: 'storeDetail',
      component: () => import('@/views/detail/StoreDetail.vue')
    },
    {
      path: '/wholesalerDetail/:userId',
      name: 'wholesalerDetail',
      component: () => import('@/views/detail/WholesalerDetail.vue')
    },
    {
      path: '/factoryDetail/:userId',
      name: 'factoryDetail',
      component: () => import('@/views/detail/FactoryDetail.vue')
    },
    {
      path: '/order',
      component: () => import('@/views/order/order.vue')
    },
    {
      path: '/orderPay',
      component: () => import('@/views/order/orderPay.vue')
    },
    {
      path: '/orderOk',
      component: () => import('@/views/order/orderOK.vue')
    },
    {
      path: '/customer/:userId',
      name: 'customer',
      component: () => import('@/views/customer/index.vue')
    },
    {
      path: '/cashier',
      name: 'cashier',
      component: () => import('@/views/cashier/index.vue')
    },
    {
      path: '/cashier/order',
      name: 'order',
      component: () => import('@/views/cashier/components/order.vue')
    },
    {
      path: '/cashier/inventory',
      name: 'inventory',
      component: () => import('@/views/cashier/components/inventory.vue')
    }
  ],
  scrollBehavior() {
    return {
      top: 0
    }
  }
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const tokenStore = useTokenStore()
  const isLoggedIn = tokenStore.token !== ''
  const userRole = Number(tokenStore.user?.identity)  // 转换为数字类型
  // console.log(isLoggedIn)
  // console.log(typeof userRole)

  // 不需要登录的路由
  const publicPages = ['/', '/login', '/register']
  const isPublicPage = publicPages.includes(to.path)

  //测试全部放行
  // next()

  // 如果路由需要认证
  if (to.meta.requiresAuth) {
    // 未登录，跳转到登录页
    if (!isLoggedIn) {
      ElMessage.error('请先登录')
      next('/login')
      return
    }

    // 已登录但角色不匹配，跳转到对应的管理页面
    if (to.meta.role !== userRole) {
      // 根据用户角色跳转到对应页面
      const rolePages = {
        0: '/member',
        1: '/store',
        2: '/wholesaler',
        3: '/factory'
      }
      // 避免重复跳转到同一页面
      if (to.path !== rolePages[userRole]) {
        next(rolePages[userRole])
        return
      }
    }
  }
  // 其他情况放行
  console.log('其他情况放行')
  next()
})

export default router
